package com.example.administrator.yongleapp.View.Fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;

import com.example.administrator.yongleapp.Adapterqzn.FilmAdapter;
import com.example.administrator.yongleapp.Base.BaseFragment;
import com.example.administrator.yongleapp.Bean.liujiahe.FilmBean;
import com.example.administrator.yongleapp.R;
import com.example.administrator.yongleapp.View.Activity.ActivitiesDetaisAc;
import com.example.administrator.yongleapp.decoration.DividerGridItemDecoration;
import com.example.administrator.yongleapp.utils.Constantqzn;
import com.example.administrator.yongleapp.utils.OkhttpHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * ----------BigGod be here!----------/
 * ***┏┓******┏┓*********
 * *┏━┛┻━━━━━━┛┻━━┓*******
 * *┃             ┃*******
 * *┃     ━━━     ┃*******
 * *┃             ┃*******
 * *┃  ━┳┛   ┗┳━  ┃*******
 * *┃             ┃*******
 * *┃     ━┻━     ┃*******
 * *┃             ┃*******
 * *┗━━━┓     ┏━━━┛*******
 * *****┃     ┃神兽保佑*****
 * *****┃     ┃代码无BUG！***
 * *****┃     ┗━━━━━━━━┓*****
 * *****┃              ┣┓****
 * *****┃              ┏┛****
 * *****┗━┓┓┏━━━━┳┓┏━━━┛*****
 * *******┃┫┫****┃┫┫********
 * *******┗┻┛****┗┻┛*********
 * ━━━━━━神兽出没━━━━━━
 * Administrator on 2016/7/6.
 * Class description:活动
 * Created by:qzn
 * Creation time:2016/7/7.
 * Modified by:qzn
 * Modified time:2016/7/7.
 * Modified remarks:
 */
public class FilmFragment extends BaseFragment {
    private static final String TAG = "FilmFragment";
    public static List<FilmBean.DataBean.PromotionLinkListBean.ProductsBean> list=new ArrayList<>();
    @Bind(R.id.recyclerView_film)
    RecyclerView recyclerViewActivity;
    @Bind(R.id.ptrFrameLayout_film)
    PtrFrameLayout ptrFrameLayoutActivity;
    private FilmAdapter mAdapter;
    private int curpage = 1;
    private List<FilmBean.DataBean.PromotionLinkListBean> totallist = new ArrayList<>();
    private int lastVisibleItem = 0;
    @Override
    public int getLayoutId() {
        return R.layout.fragment_film;
    }

    @Override
    public void initView() {
        recyclerViewActivity.addItemDecoration(new DividerGridItemDecoration(getContext()));

        //设置item有相同的高度，提高效率
        recyclerViewActivity.setHasFixedSize(true);
        //设置网格布局
        final LinearLayoutManager managerLayout = new LinearLayoutManager(getContext());
        recyclerViewActivity.setLayoutManager(managerLayout);

        //设置动画效果
        recyclerViewActivity.setItemAnimator(new DefaultItemAnimator());
        getActivityData();
        mAdapter = new FilmAdapter(getContext(), totallist,
                recyclerViewActivity);
        mAdapter.setOnItemClickedListener(new FilmAdapter.OnItemClickedListener() {
            @Override
            public void onItemClick(int postion) {
                // 跳到活动详情的页面
                Intent intent = new Intent();
                intent.setClass(getActivity(), ActivitiesDetaisAc.class);
                list=totallist.get(postion).getProducts();
                Log.i(TAG, "--->>list: "+list);
                Bundle bundle = new Bundle();
                bundle.putString("remark",totallist.get(postion).getRemark());
                intent.putExtra("text", totallist.get(postion).getText());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        getActivityData();
        recyclerViewActivity.setAdapter(mAdapter);
//上拉加载下一页
        recyclerViewActivity.addOnScrollListener(new RecyclerView
                .OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (lastVisibleItem + 1 == mAdapter.getItemCount() &&
                        newState ==
                                RecyclerView.SCROLL_STATE_IDLE) {//停止滑动了
                    curpage++;

                    getActivityData();

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = managerLayout.findLastVisibleItemPosition();
            }
        });

        //使用PtrFrameLayout实现下拉刷新x
        //效果1：设置默认的经典的头标
        PtrClassicDefaultHeader defaultHeaderEditor = new PtrClassicDefaultHeader
                (getContext());
        //设置头视图
        ptrFrameLayoutActivity.setHeaderView(defaultHeaderEditor);
        //绑定UI与刷新
        ptrFrameLayoutActivity.addPtrUIHandler(defaultHeaderEditor);
        //添加刷新动作监听
        ptrFrameLayoutActivity.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                curpage = 1;
                getActivityData();


            }

        });



    }


    /**
     * 加载活动数据
     */
    private void getActivityData( ){
        OkhttpHelper.getInstance().get(Constantqzn.ACTIVITY.replace("%d",curpage+""), new OkhttpHelper.CallBack() {
            @Override
            public void onSuccess(String json) {
                final List<FilmBean.DataBean.PromotionLinkListBean> totallist = getActivityB(json)
                        .getData().getPromotionLinkList();
                if (totallist==null){
                    Toast.makeText(getActivity(), "已经到了最后一页", Toast.LENGTH_SHORT).show();
                }else{
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            if (curpage == 1) {
                                mAdapter.reloadListView
                                        (totallist, true);
                            } else {
                                mAdapter.reloadListView
                                        (totallist, false);
                            }
                            ptrFrameLayoutActivity.refreshComplete();
                        }
                    });
                }


            }

            @Override
            public void onFailure() {
                Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_SHORT).show();
            }
        });


    }
    /**
     * 获得活动Bean
     *
     * @param jsonString json字符串
     * @return bean
     */
    private FilmBean getActivityB(String jsonString) {
        Gson gson = new Gson();
        FilmBean model = gson.fromJson(jsonString, new TypeToken<FilmBean>() {
        }.getType());
        return model;
    }
}
